package main

import (
	"encoding/json"
	"fmt"
	"reflect"
	"strconv"

	"yingsheng.com/go-api-server"
	"yingsheng.com/go-api-server/errors"
	"yingsheng.com/go-api-server/mq"
)

var (
	in           *SChain
	Nsqinst      NsqStruct
	testConsumer mq.ConsumerInterface
)

type NsqStruct struct {
}

func Init() {
	var err error

	// 注册RPC
	apiserver.AddRpcService(&Nsqinst)
	// 创建消息消费者对象
	testConsumer, err = mq.NewConsumer("nsq", "test2", "ch1", &Nsqinst)
	if err != nil {
		fmt.Println("Consumer New Error: ", err)
		apiserver.Error("Consumer New Error:" + err.Error())
	} else {
		apiserver.Info("Consumer running...")
		fmt.Println("Consumer running...")
	}
}

func (t *NsqStruct) HandlerMessage(msg []byte) error {
	apiserver.Info("get data from nsq:", string(msg))
	result := make(map[string]interface{})
	json.Unmarshal(msg, &result)

	fmt.Println("nsq_example --> HandlerMessage --> result:", result)

	//	fmt.Println("nsq_example --> HandlerMessage --> appsecret:",result["appsecret"].(string))
	//	fmt.Println("nsq_example --> HandlerMessage --> appkey:",result["appkey"].(string))
	//	fmt.Println("nsq_example --> HandlerMessage --> catid:",result["catid"].(string))
	//	fmt.Println("nsq_example --> HandlerMessage --> timestamp:",result["timestamp"].(string))

	transtype := result["transtype"]
	if transtype != "" {
		switch {
		case transtype == "chainlog":
			func() {
				in = &SChain{
					ChainID:    helper(result["chainid"]),
					AppKey:     helper(result["appkey"]),
					ActionName: helper(result["actionname"]),
					Parameters: helper(result["parameters"]),
					ErrorInfo:  helper(result["errorinfo"]),
					Response:   helper(result["response"]),
				}
			}()
		default:
			//nokown type of data to stored
			apiserver.Error("nokown type of data to stored")
			return errors.New("nokown type of data to stored")
		}

	} else {
		//no telling what kind of data to transfer
		apiserver.Error("no telling what kind of data to transfer")
		return errors.New("no telling what kind of data to transfer")
	}
	var ret int64

	basemsg := fmt.Sprintf("Insert data to table %s", reflect.ValueOf(in).MethodByName("TableName").Call([]reflect.Value{}))

	fmt.Println("basemsg:", basemsg)
	ret, err = da.Insert(in)
	if err != nil {
		errmsg := basemsg + "error ,reason :" + err.Error()
		apiserver.Error(errmsg)
	} else {
		info := basemsg + "success ,size :" + strconv.FormatInt(ret, 10)
		apiserver.Info(info)
	}
	return nil
}

func helper(v interface{}) string {
	if v == nil {
		return string("")
	} else {
		return v.(string)
	}
	return string("")
}
func (*NsqStruct) Stop() {
}
